package com.aliyun.heiyu.powermaster.server.manager;

import com.aliyun.heiyu.common.util.*;
import com.aliyun.heiyu.powermaster.proto.*;
import com.aliyun.heiyu.powermaster.server.Error;
import com.aliyun.heiyu.powermaster.server.RequestData;
import com.aliyun.heiyu.powermaster.server.SetPowerEntity;
import com.aliyun.heiyu.powermaster.server.dao.*;
import com.aliyun.heiyu.powermaster.server.dao.entity.DeviceCommonEntity;
import com.aliyun.heiyu.powermaster.server.dao.entity.StateGridCapTaskItemEntity;
import com.aliyun.heiyu.powermaster.server.dao.enums.DeviceUsageStatusEnum;
import com.aliyun.heiyu.powermaster.server.dao.impl.*;
import com.aliyun.heiyu.powermaster.server.factory.TransDeviceManager;
import com.aliyun.heiyu.powermaster.server.rotary.dao.AirDAO;
import com.aliyun.heiyu.powermaster.server.rotary.dao.PduDAO;
import com.aliyun.heiyu.powermaster.server.rotary.dao.impl.AirDAOImpl;
import com.aliyun.heiyu.powermaster.server.rotary.dao.impl.PduDAOImpl;
import com.aliyun.heiyu.powermaster.server.rotary.object.entity.PduDataDynEntity;
import com.aliyun.heiyu.powermaster.server.rotary.object.entity.PduDataElectricEntity;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.client.utils.URIBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.text.DecimalFormat;
import java.util.*;

public class ThunderManagerImpl implements ThunderManager {
    private static Logger logger = LoggerFactory.getLogger(ThunderManagerImpl.class);

    private StateGridCollectInfoDao serverInfoDao;
    private DeviceManager deviceManager;
    private AirDAO airDAO;
    private String host;
    private Integer port;
    private PduDAO pduDAO;
    private DeviceSpecDao ipcDao;
    private DeviceServerDao deviceServerDao;
    private ArmStateGridCollectInfoDao armStateGridCollectInfoDao;
    private DictionaryConfigDao dictionaryConfigDao =new DictionaryConfigDaoImpl();

    public ThunderManagerImpl() {
        this.host = PropertiesUtil.getValue("serverIp.properties", "serverIp");
        this.port = Integer.parseInt(PropertiesUtil.getValue("serverIp.properties", "thunderPort"));
        this.serverInfoDao = new StateGridCollectInfoImpl();
        this.deviceManager = TransDeviceManager.getDeviceServiceTrans();
        this.airDAO = new AirDAOImpl();
        this.pduDAO = new PduDAOImpl();
        this.ipcDao = new DeviceSpecIpcImpl();
        this.deviceServerDao = new DeviceServerDaoImpl();
        this.armStateGridCollectInfoDao = new ArmStateGridCollectInfoDaoImpl();
    }

    //获取某个设备的所有动态数据信息
    @Override
    public Map<String, String> getPowerInfoData(String sn, String type) {
        Map<String, String> info = new HashMap<>();
        if ("server".equals(type)) {
            //TODO
            String serverType = deviceServerDao.selectServerType(sn);
            if("arm".equals(serverType)){
                info=getArmServerPowerInfo(sn);
            }else{
                info = getServerPowerInfo(sn);
            }

        } else if ("cabinet".equals(type)) {
            info = getCabinetPowerInfo(sn);
        } else if ("air".equals(type)) {
            /**获取空调动态数据*/
            info = airDAO.getAirDynamic(sn);
            if (info != null) {
                info.put("server_sn", sn);
                if (!info.containsKey("room_temperature") || StringUtil.isEmpty(info.get("room_temperature")) || Double.parseDouble(info.get("room_temperature")) == 0) {
                    info.put("power", "0");
                } else {
                    if (Double.parseDouble(info.get("room_temperature")) < 17) {
                        info.put("power", "0");
                    } else {
                        info.put("power", String.valueOf(keepTwoDecimals((Double.valueOf(info.get("room_temperature")) - 11) * 0.721 * 1000)));
                    }
                }
            }
        } else if ("pdu".equals(type)) {
            info = getPduPowerInfoByDeviceId(sn);
            if (info != null) {
                info.put("server_sn", sn);
            }
        } else if ("ipc".equals(type)) {
            info = ipcDao.findOne(sn);
            if (info != null) {
                info.put("server_sn", sn);
            }
        } else {
            logger.warn("don't find this device type");
            return info;
        }
        return info;
    }

    private Map<String, String> getArmServerPowerInfo(String sn) {
        Map<String, String> map=armStateGridCollectInfoDao.getArmStateGridCollectInfo(sn);
        if (map != null) {
            String collectTime = map.get("collect_time");
            if (!checkPowerStatus(collectTime)) {
                return null;
            }
            map.put("power", map.get("server_power"));
            int cpuFreq = getAvgFreq(map.get("cpu_freq"));
            map.put("cpu_freq", String.valueOf(cpuFreq));
            if (!StringUtil.isEmpty(map.get("cpu_usage"))) {
                BigDecimal b = new BigDecimal(map.get("cpu_usage"));
                b = b.setScale(3, BigDecimal.ROUND_HALF_UP);
                map.put("cpu_usage", String.valueOf(b));
            }
            //去掉多余不用字段
            map.remove("core_util");
            map.remove("nvme_temp_max");
        }
        return map;
    }

    //获取某个设备的PowerInfo对象
    @Override
    public PowerInfo getPowerInfo(String sn, String type) {
        Map<String, String> info = getPowerInfoData(sn, type);
        if (info != null && info.size() > 0) {
            return mapToPowerInfo(info);
        }
        return null;
    }

    @Override
    public PowerInfo getPowerInfo(String sn) {
        DeviceCommonEntity device = deviceManager.findOneDeviceCommon(sn);
        if (device != null) {
            return getPowerInfo(sn, device.getType());
        }
        return null;
    }

    /**
     * 通过设备静态数据集合得到对应的设备的PowerInfo集合
     *
     * @param deviceCommonList NOTNULL
     * @return NOTNULL
     */
    @Override
    public Map<String, PowerInfo> getPowerInfo(List<DeviceCommonEntity> deviceCommonList) {
        ArrayList<String> serverIdList = new ArrayList<>();
        HashMap<String, PowerInfo> powerInfoMap = new HashMap<>();
        for (DeviceCommonEntity deviceCommonEntity : deviceCommonList) {
            String deviceId = deviceCommonEntity.getDevice_id();
            String deviceType = deviceCommonEntity.getType();
            if ("server".equals(deviceType)) {
                serverIdList.add(deviceId);
            } else {
                PowerInfo powerInfo = getPowerInfo(deviceId, deviceType);
                if (powerInfo != null) {
                    powerInfoMap.put(deviceId, powerInfo);
                }
            }
        }
        String[] serverIdArray = serverIdList.toArray(new String[0]);
        powerInfoMap.putAll(getServerPowerInfo(serverIdArray));
        return powerInfoMap;
    }

    @Override
    public Map<String, PowerInfo> getServerPowerInfo(List<DeviceCommonEntity> deviceCommonList) {
        ArrayList<String> serverIdList = new ArrayList<>();
        HashMap<String, PowerInfo> powerInfoMap = new HashMap<>();
        for (DeviceCommonEntity deviceCommonEntity : deviceCommonList) {
            String deviceId = deviceCommonEntity.getDevice_id();
            String deviceType = deviceCommonEntity.getType();
            if ("server".equals(deviceType)) {
                serverIdList.add(deviceId);
            }
        }
        String[] serverIdArray = serverIdList.toArray(new String[0]);
        powerInfoMap.putAll(getServerPowerInfo(serverIdArray));
        return powerInfoMap;
    }

    @Override
    public Map<String, PowerInfo> getServerPowerInfo(String[] serverIdArray) {
        HashMap<String, PowerInfo> powerInfoMap = new HashMap<>();
        //count扩大2倍,将结果排重 预防数据库中的数据设备多导致的时间误差
        int length = serverIdArray.length;
        if (serverIdArray == null || length == 0) {
            return powerInfoMap;
        }

        int serverLength = deviceManager.getTotalCount(null, null, "server", null, null, null);
        List<Map<String, String>> serverInfos = serverInfoDao.findSizeInfo(serverLength);
        //todo 通过最近时间sql查询，避免超前时间的假数据
        if (serverInfos == null || serverInfos.size() < 1) {
            return powerInfoMap;
        }
        Map<String, String> firstServerInfo = serverInfos.get(0);
        String collectTime = firstServerInfo.get("collect_time");
        if (!checkPowerStatus(collectTime)) {
            return powerInfoMap;
        }
        HashSet<String> idArraySet = new HashSet<>(Arrays.asList(serverIdArray));
        long time = DateUtil.dateToMillisecond(collectTime);
        HashSet<String> deviceIds = new HashSet<>();

        for (Map<String, String> map : serverInfos) {
            String deviceSn = map.get("server_sn");
            if (StringUtil.isEmpty(deviceSn)) {
                continue;
            }
            if (!idArraySet.contains(deviceSn)) {
                continue;
            }
            //过滤重复设备Id的数据
            if (deviceIds.contains(deviceSn)) {
                continue;
            }
            long time1 = DateUtil.dateToMillisecond(map.get("collect_time"));
            if (time1 > time + 30 * 1000 || time1 < time - 30 * 1000) {
                //时间过滤，前后 30秒时间间隔为同一次的采集时间
                continue;
            }
            deviceIds.add(deviceSn);
            int cpuFreq = getAvgFreq(map.get("cpu_freq"));
            map.put("cpu_freq", String.valueOf(cpuFreq));
            map.put("power", map.get("server_power"));
            PowerInfo powerInfo = mapToPowerInfo(map);
            powerInfoMap.put(deviceSn, powerInfo);
        }

        return powerInfoMap;
    }

    @Override
    public Map<String, PowerInfo> getAllServerPowerInfo() {
        List<DeviceCommonEntity> allDeviceCommon = deviceManager.findByType("server");
        if (allDeviceCommon == null || allDeviceCommon.size() == 0) {
            return new HashMap<>();
        }
        return getPowerInfo(allDeviceCommon);
    }

    @Override
    public List<PowerInfo> getServerPowerInfoByTime(String[] sns, String startTime, String endTime) {
        //sns为null或者为空 表示查询当前所有可采集服务器设备
        ArrayList<PowerInfo> infos = new ArrayList<>();
        List<Map<String, String>> infoList = serverInfoDao.findBySnArray(sns, startTime, endTime);
        if (infoList == null || infoList.size() < 1) {
            logger.warn("param have exception, don't have more data");
            return infos;
        }
        for (Map<String, String> map : infoList) {
            map.put("power", map.get("server_power"));
            int cpuFreq = getAvgFreq(map.get("cpu_freq"));
            map.put("cpu_freq", String.valueOf(cpuFreq));
            PowerInfo powerInfo = mapToPowerInfo(map);
            if (powerInfo != null) {
                infos.add(powerInfo);
            }
        }
        return infos;
    }

    @Override
    //1 打开， 2 关闭 Dvfs
    public Boolean operateDvfs(int action, String sn) {
        DeviceCommonEntity entity = deviceManager.findOneDeviceCommon(sn);
        if (entity == null || StringUtil.isEmpty(entity.getIp())) {
            logger.debug("设备 {} 为空或者设备属性信息不全", sn);
            return null;
        }
        String ip = entity.getIp();
        logger.info("设备IP == " + ip);
        String host = PropertiesUtil.getValue("serverIp.properties", "serverIp");
        //请求协议
        String requestAgreement="http";//http/https
        String path="/stateGrid/dvfs/setDvfs";//接口路径
        int port = this.port;
        //获取服务器类型
        String serverType = deviceServerDao.selectServerType(sn);
        String deviceSwitch= dictionaryConfigDao.getValue("deviceSwitch");
        if("arm".equals(serverType) || deviceSwitch.equals("open")){
            requestAgreement="https";
            path="/stateGrid/powerctl_agent/dvfs/set_dvfs";
            port=32345;
            host=ip;
        }
        try {
            URIBuilder uriBuilder = null;
            if("arm".equals(serverType)|| deviceSwitch.equals("open")){
                uriBuilder = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path);
            }else{
                uriBuilder = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path)
                    .setParameter("serverIp", ip);
            }

            if (action == 1) {
                uriBuilder.setParameter("enable", "1");
            } else if (action == 2) {
                uriBuilder.setParameter("enable", "0");
            }
            JSONObject jsonObject = HttpUtil.getRequest(uriBuilder.build());
            logger.debug("url == {}", uriBuilder.build().toString());
            if("arm".equals(serverType) || deviceSwitch.equals("open")){
                if (jsonObject == null || !jsonObject.get("err_code").equals(0)) {
                    logger.error("访问服务器失败,");//请求失败
                    return null;
                }
            }else{
                if (jsonObject == null || !jsonObject.getBoolean("success")) {
                    logger.error("访问服务器失败,");//请求失败
                    return null;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }


    @Override
    public Boolean getStatusOfDvfs(String sn) {
        DeviceCommonEntity entity = deviceManager.findOneDeviceCommon(sn);
        if (entity == null || StringUtil.isEmpty(entity.getIp())) {
            logger.debug("设备 {} 为空或者设备属性信息不全", sn);
            return null;
        }
        String ip = entity.getIp();
        logger.info("设备IP == "+ip);
        String host = PropertiesUtil.getValue("serverIp.properties", "serverIp");
        //请求协议
        String requestAgreement="http";//http/https
        String path="/stateGrid/dvfs/getDvfsInfo";//接口路径
        int port = this.port;
        //获取服务器类型
        String serverType = deviceServerDao.selectServerType(sn);
        String deviceSwitch= dictionaryConfigDao.getValue("deviceSwitch");
        if("arm".equals(serverType) || deviceSwitch.equals("open")){
            requestAgreement="https";
            path="/stateGrid/powerctl_agent/dvfs/check_dvfsInfo";
            port=32345;
            host=ip;
        }

        try {
            URI uri = new URIBuilder().setScheme(requestAgreement)
                .setHost(host)
                .setPort(port)
                .setPath(path)
                .setParameter("serverIp", ip)
                .build();
            JSONObject jsonObject= HttpUtil.getRequest(uri.toString());
            logger.debug("url == {}", uri.toString());
            if("arm".equals(serverType)|| deviceSwitch.equals("open")){
                if (jsonObject == null || !jsonObject.get("err_code").equals(0)) {
                    logger.error("访问服务器失败");//请求失败
                    return null;
                }
            }else{
                if (jsonObject == null || !jsonObject.getBoolean("success")) {
                    logger.error("访问服务器失败");//请求失败
                    return null;
                }
            }
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("coreDvfs");
            if (jsonArray == null || jsonArray.length() < 1) {
                return null;
            }
            String status = jsonArray.getJSONObject(0).getString("state");
            if ("enable".equals(status)) {
                return true;
            } else if ("disable".equals(status)) {
                return false;
            }
        } catch (Exception e) {
            logger.error(" com.aliyun.heiyu.powermaster.server.manager.getStatusOfDvfs:【{}】",e.getMessage());
        }
        return null;
    }

    /***
     * 获取服务器状态
     * @param sn
     * @return
     */
    @Override
    public Boolean getStatusOfCstate(String sn) {
        DeviceCommonEntity entity = deviceManager.findOneDeviceCommon(sn);
        if (entity == null || StringUtil.isEmpty(entity.getIp())) {
            logger.debug("设备 "+sn+" 为空或者设备属性信息不全");
            return null;
        }
        //arm 占时不需要这个策略
        String serverType = deviceServerDao.selectServerType(sn);
        if("arm".equals(serverType)){
            return null;
        }
        String ip = entity.getIp();
        logger.debug("设备IP == "+ip);
        String host = PropertiesUtil.getValue("serverIp.properties", "serverIp");
        //请求协议
        String requestAgreement="http";//http/https
        String path="/stateGrid/cstate/getCstateInfo";//接口路径
        int port = this.port;
        String deviceSwitch= dictionaryConfigDao.getValue("deviceSwitch");
        if(deviceSwitch.equals("open")){
            path="/stateGrid/powerctl_agent/cstate/check_cstateInfo";
            requestAgreement="https";
            port=32345;
            host=ip;
        }
        try {
            URI uri = null;
            uri = new URIBuilder().setScheme(requestAgreement)
                .setHost(host)
                .setPort(port)
                .setPath(path)
                .setParameter("serverIp", ip)
                .build();
            logger.debug("url == {}", uri.toString());
            JSONObject jsonObject =  HttpUtil.getRequest(uri.toString());
            if(deviceSwitch.equals("open")){
                if (jsonObject == null || !jsonObject.get("err_code").equals(0)) {
                    logger.error("访问服务器失败url【{}】,",uri.toString());//请求失败
                    return null;
                }
            }else{
                if (jsonObject == null || !jsonObject.getBoolean("success")) {
                    logger.error("访问服务器失败url【{}】,",uri.toString());//请求失败
                    return null;
                }
            }

            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("coreCstate");
            JSONObject jsonObject1 = jsonArray.getJSONObject(0);
            String b1 ="" ;
            String b2 = "";
            String b3 = "";
            if(deviceSwitch.equals("open")){
                b1 = jsonObject1.getString("C1");
                b2 = jsonObject1.getString("C1E");
                b3 = jsonObject1.getString("C6");
            }else{
                b1 = jsonObject1.getString("c1");
                b2 = jsonObject1.getString("c1e");
                b3 = jsonObject1.getString("c6");
            }
            if ("enable".equals(b1) && "enable".equals(b2) && "enable".equals(b3)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("com.aliyun.heiyu.powermaster.server.manager.getStatusOfCstate:【{}】",e.getMessage());
        }
        return null;
    }

    //todo ip 换成设备id，动作换成thunder接口操作
    @Override
    public Boolean operateCstate(int action, String sn) {
        DeviceCommonEntity entity = deviceManager.findOneDeviceCommon(sn);
        if (entity == null || StringUtil.isEmpty(entity.getIp())) {
            logger.debug("设备 {} 为空或者设备属性信息不全", sn);
            return null;
        }
        //arm服务器从逻辑上不会触发这个操作
        //请求协议
        String requestAgreement="http";//http/https
        String path="/stateGrid/cstate/setCstate";//接口路径
        String ip = entity.getIp();
        int port = this.port;
        logger.debug("设备IP == {}", ip);
        String host = PropertiesUtil.getValue("serverIp.properties", "serverIp");

        String deviceSwitch= dictionaryConfigDao.getValue("deviceSwitch");
        if(deviceSwitch.equals("open")){
            path="/stateGrid/powerctl_agent/cstate/set_cstate";
            requestAgreement="https";
            port=32345;
            host=ip;
        }
        try {
            URIBuilder builder1=null;
            URIBuilder builder2=null;
            URIBuilder builder3=null;
            if(deviceSwitch.equals("open")){
                builder1 = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path);
                builder2 = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path);
                builder3 = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path);
                builder1.setParameter("cstate", "C1");
                builder2.setParameter("cstate", "C1E");
                builder3.setParameter("cstate", "C6");
            }else{
                builder1 = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path)
                    .setParameter("serverIp", ip);
                builder2 = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path)
                    .setParameter("serverIp", ip);
                builder3 = new URIBuilder().setScheme(requestAgreement)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path)
                    .setParameter("serverIp", ip);
                builder1.setParameter("cstate", "C1");
                builder2.setParameter("cstate", "C1E");
                builder3.setParameter("cstate", "C6");
            }
            if (action == 1) {
                builder1.setParameter("enable", "1");
                builder2.setParameter("enable", "1");
                builder3.setParameter("enable", "1");
            }
            if (action == 2) {
                builder1.setParameter("enable", "0");
                builder2.setParameter("enable", "0");
                builder3.setParameter("enable", "0");
            }
            logger.debug("url == {}" , builder1.build().toString());
            JSONObject jsonObject1 = HttpUtil.getRequest(builder1.build());
            JSONObject jsonObject2 = HttpUtil.getRequest(builder2.build());
            JSONObject jsonObject3 = HttpUtil.getRequest(builder3.build());
            if(deviceSwitch.equals("open")){
                if (jsonObject1 == null || !jsonObject1.get("err_code").equals(0)) {
                    logger.error("访问服务器失败c1");//请求失败
                    return null;
                }

                if (jsonObject2 == null || !jsonObject2.get("err_code").equals(0)) {
                    logger.error("访问服务器失败c1e");//请求失败
                    return null;
                }

                if (jsonObject3 == null || !jsonObject3.get("err_code").equals(0)) {
                    logger.error("访问服务器失败c6");//请求失败
                    return null;
                }
            }else{
                if (jsonObject1 == null || !jsonObject1.getBoolean("success")) {
                    logger.error("访问服务器失败c1");//请求失败
                    return null;
                }

                if (jsonObject2 == null || !jsonObject2.getBoolean("success")) {
                    logger.error("访问服务器失败c1e");//请求失败
                    return null;
                }

                if (jsonObject3 == null || !jsonObject3.getBoolean("success")) {
                    logger.error("访问服务器失败c6");//请求失败
                    return null;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }

    public Boolean getStatusOfCapping(String sn) {
        StateGridCapTaskItemDao dao = new StateGridCapTaskItemImpl();
        DeviceCommonEntity device = deviceManager.findOneDeviceCommon(sn);
        if (device == null || StringUtil.isEmpty(device.getIp())) {
            return null;
        }
        String ip = device.getIp();
        StateGridCapTaskItemEntity lastOne = dao.findLastOne(ip);
        if (lastOne == null) {
            return false;
        }
        String param = lastOne.getParam();
        if (param == null || "-1".equals(param)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Boolean getStatusOfPowerOff(String sn) {
        DeviceCommonEntity entity = deviceManager.findOneDeviceCommon(sn);
        if (entity == null || StringUtil.isEmpty(entity.getUsage_status())) {
            return null;
        }
        String usageStatus = entity.getUsage_status();
        if (DeviceUsageStatusEnum.DEVICE_POWEROFF.getMsg().equals(usageStatus)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Capping: 一次动作，一台机器
     */
    @Override
    public Boolean setPower(SetPowerRequest request) {
        ArrayList<SetPowerEntity> listSetPower = new ArrayList<>();
        //把label当做设备编号使用。
        String sn = request.getLabel();
        DeviceCommonEntity deviceCommon = deviceManager.findOneDeviceCommon(sn);
        if ("server".equals(deviceCommon.getType())) {
            SetPowerEntity setPowerEntity = new SetPowerEntity();
            setPowerEntity.setServerIp(deviceCommon.getIp()); //获取设备ID
            //判断需要capping，并设置具体值
            if (request.getStrategyValue() == PowerStrategy.CAPPING_POWER.getNumber()) {
                setPowerEntity.setCapAction(true);
                //通过设备的额定功率计算capping的PowerLimit值，并设置
                if (request.getPowerLimit() != 0) {
                    setPowerEntity.setPowerLimit(request.getPowerLimit());
                } else {
                    setPowerEntity.setPowerLimit((int) StringUtil.convertDouble(deviceCommon.getRated_power()) * request.getCapRate() / 100);
                }
                setPowerEntity.setFreqLimit(request.getMinFreq());
            } else {
                setPowerEntity.setCapAction(false);
            }
            listSetPower.add(setPowerEntity);
        }
        if (listSetPower.size() > 0) {
            //从配置文件获取对应的ip
            String host = PropertiesUtil.getValue("serverIp.properties", "setPowerUrl");
            //对参数做处理转化为json
            String json = new JSONArray(listSetPower).toString();
            //创建http连接调用第三方接口
            JSONObject jsonObject = HttpUtil.postRequest(json, host);
            if (jsonObject == null || !jsonObject.getBoolean("success")) {
                logger.error("访问服务器失败");//请求失败
                return null;
            }
        }
        return true;
    }

    public GetWarningDataReply getWarningData() {
        GetWarningDataReply.Builder builder = GetWarningDataReply.newBuilder();
        Map<String, String> resultMap = new HashMap<>();
        RequestData loginData = new RequestData();
        loginData.setVersion(PropertiesUtil.getValue("serverIp.properties", "version"));
        Map<String, Object> data = new HashMap<>();
        data.put("ip", PropertiesUtil.getValue("serverIp.properties", "userIp"));
        data.put("username", PropertiesUtil.getValue("serverIp.properties", "userUsername"));
        data.put("password", PropertiesUtil.getValue("serverIp.properties", "userPassword"));
        data.put("login_time", System.currentTimeMillis() / 1000);
        loginData.setData(data);
        try {
            String loginRequest = new JSONObject(loginData).toString();
            String loginResult = HttpUtil.postJson(PropertiesUtil.getValue("serverIp.properties", "loginUrl"), null, loginRequest);
            if (loginResult == null || "".equals(loginResult)) {
                logger.error("loginResult is null ");
            }
            String token = new JSONObject(loginResult).getJSONObject("data").get("token").toString();
            RequestData onlineData = new RequestData();
            onlineData.setVersion(PropertiesUtil.getValue("serverIp.properties", "version"));
            Map<String, Integer> map = new HashMap<>();
            map.put("begin_time", new Long(System.currentTimeMillis() / 1000).intValue());
            map.put("end_time", new Long(System.currentTimeMillis() / 1000).intValue() - 86400);
            onlineData.setData(map);
            String onlineJson = new JSONObject(onlineData).toString();
            String onlineResult = HttpUtil.postJson("http://10.146.168.100:8888/north/offline_alarm_get", token, onlineJson);
            if (onlineResult == null || "".equals(onlineResult)) {
                logger.warn("onlineResult is null");
            }
            JSONArray alarms = new JSONObject(onlineResult).getJSONObject("data").getJSONArray("alarms");
            for (int i = 0; i < alarms.length(); i++) {
                JSONObject jsonObject = alarms.getJSONObject(i);
                resultMap.put("serial_number", jsonObject.get("serial_number") + "");
                resultMap.put("guid", jsonObject.get("guid") + "");
                resultMap.put("trigger_time", jsonObject.get("trigger_time") + "");
                resultMap.put("content", jsonObject.get("content") + "");
                resultMap.put("trigger_snapshot", jsonObject.get("trigger_snapshot") + "");
                resultMap.put("alarm_level", jsonObject.get("alarm_level") + "");
                resultMap.put("alarm_type", jsonObject.get("alarm_type") + "");
                resultMap.put("suggestion", jsonObject.get("suggestion") + "");
                resultMap.put("ecover_time", jsonObject.get("ecover_time") + "");
                resultMap.put("recover_snapshot", jsonObject.get("recover_snapshot") + "");
                resultMap.put("confirm_time", jsonObject.get("confirm_time") + "");
                resultMap.put("confirm_by", jsonObject.get("confirm_by") + "");
                resultMap.put("confirm_description", jsonObject.get("confirm_description") + "");
                resultMap.put("remove_time", jsonObject.get("remove_time") + "");
                resultMap.put("remove_by", jsonObject.get("remove_by") + "");
                resultMap.put("remove_description", jsonObject.get("remove_description") + "");
                builder.addData(ResultMap.newBuilder().putAllMap(resultMap).build());

            }
        } catch (IOException e) {
            logger.debug("post请求发送异常 {}", e);
        }

        return builder.build();
    }

    public SeniorReply senior() {
        SeniorReply.Builder builder = SeniorReply.newBuilder();
        Map<String, PowerInfo> allServerPowerInfo = getAllServerPowerInfo();

        Set<String> keys = allServerPowerInfo.keySet();

        for (String key : keys) {
            String server_power = String.valueOf(allServerPowerInfo.get(key).getServerPower());

            String cpu_usage = String.valueOf(allServerPowerInfo.get(key).getCpuUsage());

            Map<String, String> device = deviceManager.findOneDeviceDetail(key);
            if (null == device || device.isEmpty()) {
                continue;
            }
            builder.addData(SeniorManagement.newBuilder().setEquipmentNumber(key).setIp(device.get("ip")).setCpuUsage(Double.valueOf(cpu_usage)).setServerPower(new BigDecimal(server_power).intValue()).build());
        }
        return builder.build();
    }

    public Map<String, String> getServerPowerInfoBefore(String sn, Integer position) {
        Map<String, String> map = serverInfoDao.findBySn(sn, position);
        if (map == null) {
            return null;
        }
        int cpuFreq = getAvgFreq(map.get("cpu_freq"));
        map.put("cpu_freq", String.valueOf(cpuFreq));
        return map;
    }

    public GetServerInfoReply getServerInfos(String field) {
        GetServerInfoReply.Builder builder = GetServerInfoReply.newBuilder();

        if (null == field || field.isEmpty()) {
            return builder.build();
        }
        String[] fields = field.split(",");
        if (null == fields || fields.length == 0) {
            return builder.build();
        }
        List<Map<String, String>> serverInfos = serverInfoDao.getServerInfos(fields);
        if (null == serverInfos || serverInfos.size() == 0) {
            return builder.build();
        }
        for (int i = 0; i < serverInfos.size(); i++) {
            Map<String, String> stringStringMap = serverInfos.get(i);
            String ip = deviceManager.findOneDeviceCommon(stringStringMap.get("server_sn")).getIp();
            stringStringMap.put("ip", ip);
            stringStringMap.remove("server_sn");
            ResultMap.Builder reBuilder = ResultMap.newBuilder();
            builder.addData(reBuilder.putAllMap(stringStringMap).build());
        }
        return builder.build();
    }

    @Override
    public ModifyAirTempReply modifyAirTemp(ModifyAirTempRequest request) {
        ModifyAirTempReply.Builder builder = ModifyAirTempReply.newBuilder();
        String airSn = request.getAirSn();
        String temp = request.getTemp();
        try {
            if (StringUtil.isEmpty(airSn) || StringUtil.isEmpty(temp)) {
                logger.error("param is empty or null");
                return builder.setErrCode(552).setErrMsg("param is empty or null").build();
            }
            String connectData = connectDyn();
            if (connectData == null || "".equals(connectData)) {
                return builder.setErrCode(550).setErrMsg("connectData is null,please check your configuration connection").build();
            }
            String guid = "";
            if ("JXKT001".equals(airSn)) {
                guid = "6F9619FF-8B86-D011-B42D-00C04FC91215.1001";
            }
            if ("JXKT002".equals(airSn)) {
                guid = "6F9619FF-8B86-D011-B42D-00C04FC91216.1044";
            }
            if ("JXKT003".equals(airSn)) {
                guid = "6F9619FF-8B86-D011-B42D-00C04FC91217.1044";
            }
            String token = new JSONObject(connectData).getJSONObject("data").get("token").toString();
            RequestData onlineData = new RequestData();
            onlineData.setVersion(PropertiesUtil.getValue("serverIp.properties", "version"));
            Map<String, Object> map = new HashMap<>();
            map.put("guid", guid);
            map.put("value", temp);
            map.put("time", System.currentTimeMillis() / 1000);
            onlineData.setData(map);
            String onlineJson = new JSONObject(onlineData).toString();
            String onlineResult = HttpUtil.postJson("http://EMS_IP:Port/north/control_set", token, onlineJson);
            if (onlineResult == null || "".equals(onlineResult)) {
                logger.error("onlineResult is null ");
                return builder.setErrCode(551).setErrMsg("onlineResult is null,please check your configuration connection").build();
            }
            JSONObject data = new JSONObject(onlineResult).getJSONObject("data");
            String resultGuid = data.get("guid").toString();
            String value = data.get("value").toString();
            if (resultGuid.equals(guid) && value.equals(temp)) {
                builder.setErrMsg(Error.SUCCESS.getMessage()).setErrCode(Error.SUCCESS.getCode());
            }
        } catch (Exception e) {
            logger.debug("post请求发送异常 {}", e);
            builder.setErrCode(553).setErrMsg(e.toString());
        }
        return builder.build();
    }

    @Override
    public PowerInfo getMaxOne(String deviceId, String startTime, String endTime) {
        Map<String, String> map = serverInfoDao.findMaxOne(deviceId, startTime, endTime);
        if (map == null) {
            return null;
        }
        PowerInfo powerInfo = mapToPowerInfo(map);
        return powerInfo;
    }


    private Map<String, String> getServerPowerInfo(String sn) {
        Map<String, String> map = serverInfoDao.findOne(sn);
        if (map != null) {
            String collectTime = map.get("collect_time");
            if (!checkPowerStatus(collectTime)) {
                return null;
            }
            map.put("power", map.get("server_power"));
            int cpuFreq = getAvgFreq(map.get("cpu_freq"));
            map.put("cpu_freq", String.valueOf(cpuFreq));
            if (!StringUtil.isEmpty(map.get("cpu_usage"))) {
                BigDecimal b = new BigDecimal(map.get("cpu_usage"));
                b = b.setScale(3, BigDecimal.ROUND_HALF_UP);
                map.put("cpu_usage", String.valueOf(b));
            }
            //去掉多余不用字段
            map.remove("core_util");
            map.remove("nvme_temp_max");
        }
        return map;
    }

    private int getAvgFreq(String freq) {
        //参数可以为null和空
        int avgFreq = 0;
        try {
            if (!StringUtil.isEmpty(freq)) {
                String[] freqs = freq.split(",");
                int length = freqs.length;
                int sumFreq = 0;
                for (String f : freqs) {
                    sumFreq += Integer.valueOf(f);
                }
                avgFreq = sumFreq / length;
                //异常数据过滤
                if (avgFreq > 3500) {
                    avgFreq = 3500;
                }
                if (avgFreq < 1000) {
                    avgFreq = 1000;
                }
            }
        } catch (Exception e) {
            avgFreq = 0;
            logger.error("FREQ数据格式异常");
        }
        return avgFreq;
    }

    private double keepTwoDecimals(double num) {

        return Double.parseDouble(new DecimalFormat("#.00").format((num)));
    }

    //时间过滤，前后 3分钟可以认为当前时间,判断是否为有效值
    private boolean checkPowerStatus(String collectTime) {
        long time = DateUtil.dateToMillisecond(collectTime);
        if (time > System.currentTimeMillis() + 3 * 60 * 1000 || time < System.currentTimeMillis() - 3 * 60 * 1000) {
            return false;
        }
        return true;
    }

    private PowerInfo mapToPowerInfo(Map<String, String> map) {
        PowerInfo.Builder builder = PowerInfo.newBuilder();
        String deviceId = map.get("server_sn");
        if (StringUtil.isEmpty(deviceId)) {
            return null;
        }
        builder.setEquipmentNumber(deviceId);
        builder.setServerPower(StringUtil.convertInt(map.get("power")));
        builder.setCpuFreq(StringUtil.convertInt(map.get("cpu_freq")));
        builder.setCpuUsage(StringUtil.convertDouble(map.get("cpu_usage")));
        if (!StringUtil.isEmpty(map.get("collect_time"))) {
            builder.setCollectTime(map.get("collect_time"));
        }
        if (!StringUtil.isEmpty(map.get("baud_rate"))) {
            builder.setBaudRate(map.get("baud_rate"));
        }
        return builder.build();
    }

    private Map<String, String> getCabinetPowerInfo(String sn) {
        //sn 非空,返回值不会为null
        int sumPower = 0;
        Map<String, String> infoMap = new HashMap<String, String>();
        List<DeviceCommonEntity> deviceCommonList = deviceManager.findByCabinet(sn);
        if (deviceCommonList == null) {
            logger.info("data is imptied");
            return infoMap;
        }
        infoMap.put("server_sn", sn);
        Map<String, PowerInfo> serverPowerInfos = getServerPowerInfo(deviceCommonList);
        Collection<PowerInfo> powerinfos = serverPowerInfos.values();
        for (PowerInfo info : powerinfos) {
            int serverPower = info.getServerPower();
            sumPower += serverPower;
        }
        infoMap.put("power", String.valueOf(sumPower));
        return infoMap;
    }

    private Map<String, String> getAirPowerInfo(String sn) {

        Map<String, String> map = new HashMap<String, String>();
        Map<String, Map<String, String>> resultMap = getDyn();
        AirConditioner.Builder b = AirConditioner.newBuilder();
        if (resultMap != null && !"".equals(resultMap) && resultMap.size() != 0) {
            if ("JXKT001".equals(sn)) {
                Map<String, String> jxkt001Map = resultMap.get("6F9619FF-8B86-D011-B42D-00C04FC91215");
                b.setRoomTemperature(jxkt001Map.get("1001")).setRoomRelativeHumidity(jxkt001Map.get("1002")).setCircuit1EvaporatingPressure(jxkt001Map.get("1003"))
                    .setCircuit2EvaporatingPressure(jxkt001Map.get("1004")).setCircuit1SuctionTemperature(jxkt001Map.get("1005")).setCircuit2SuctionTemperature(jxkt001Map.get("1006"))
                    .setCircuit1EvaporatingTemperature(jxkt001Map.get("1007")).setCircuit2EvaporatingTemperature(jxkt001Map.get("1008")).setCircuit1Superheat(jxkt001Map.get("1009"))
                    .setCircuit2Superheat(jxkt001Map.get("1010")).setEvaporatingFanSpeed(jxkt001Map.get("1045")).setCoolingSetpoint(jxkt001Map.get("1046")).setCoolingSensitivity(jxkt001Map.get("1047")).setPower(keepTwoDecimals((Double.valueOf(jxkt001Map.get("1001")) - 11) * 0.766 * 1000));
            }

            if ("JXKT002".equals(sn)) {
                Map<String, String> jxkt002Map = resultMap.get("6F9619FF-8B86-D011-B42D-00C04FC91216");
                b.setRoomTemperature(jxkt002Map.get("1044")).setRoomRelativeHumidity(jxkt002Map.get("1043")).setCircuit1EvaporatingPressure(jxkt002Map.get("1042"))
                    .setCircuit2EvaporatingPressure(jxkt002Map.get("1041")).setCircuit1SuctionTemperature(jxkt002Map.get("1040")).setCircuit2SuctionTemperature(jxkt002Map.get("1039"))
                    .setCircuit1EvaporatingTemperature(jxkt002Map.get("1038")).setCircuit2EvaporatingTemperature(jxkt002Map.get("1037")).setCircuit1Superheat(jxkt002Map.get("1036"))
                    .setCircuit2Superheat(jxkt002Map.get("1035")).setEvaporatingFanSpeed(jxkt002Map.get("1045")).setCoolingSetpoint(jxkt002Map.get("1046")).setCoolingSensitivity(jxkt002Map.get("1047")).setPower(keepTwoDecimals((Double.valueOf(jxkt002Map.get("1044")) - 11) * 0.721 * 1000));
            }

            if ("JXKT003".equals(sn)) {
                Map<String, String> jxkt003Map = resultMap.get("6F9619FF-8B86-D011-B42D-00C04FC91217");
                b.setRoomTemperature(jxkt003Map.get("1044")).setRoomRelativeHumidity(jxkt003Map.get("1043")).setCircuit1EvaporatingPressure(jxkt003Map.get("1042"))
                    .setCircuit2EvaporatingPressure(jxkt003Map.get("1041")).setCircuit1SuctionTemperature(jxkt003Map.get("1040")).setCircuit2SuctionTemperature(jxkt003Map.get("1039"))
                    .setCircuit1EvaporatingTemperature(jxkt003Map.get("1038")).setCircuit2EvaporatingTemperature(jxkt003Map.get("1037")).setCircuit1Superheat(jxkt003Map.get("1036"))
                    .setCircuit2Superheat(jxkt003Map.get("1035")).setEvaporatingFanSpeed(jxkt003Map.get("1045")).setCoolingSetpoint(jxkt003Map.get("1046")).setCoolingSensitivity(jxkt003Map.get("1047")).setPower(keepTwoDecimals((Double.valueOf(jxkt003Map.get("1044")) - 11) * 0.721 * 1000));
            }
        }
        map = airBuilderToMap(b);
        if (map != null && !map.isEmpty()) {
            map.put("server_sn", sn);
        }
        return map;
    }

    /**
     * 获取pdu动态数据
     *
     * @param sn
     * @return
     */
    public Map<String, String> getPduPowerInfoByDeviceId(String sn) {
        //支路功率
        double totalPower = 0;
        String par = "branch_power";
        PDU.Builder pBuilder = PDU.newBuilder();
        Map<String, String> map = pduBuilderToMap(pBuilder);
        List<PduDataDynEntity> powerList = pduDAO.getPowerListByDeviceId(sn);
        if (CollectionUtils.isEmpty(powerList)) {
            return map;
        }
        for (PduDataDynEntity pdu : powerList) {
            StringBuffer param = new StringBuffer();
            param.append(par).append(pdu.getBranch_number());
            map.put(param.toString(), String.valueOf(pdu.getBranch_power()));
            totalPower = totalPower + pdu.getBranch_power();
        }
        map.put("total_power", String.valueOf(totalPower));
        map.put("power", String.valueOf(totalPower));
        //支路电流
        String electric = "branch_electric";
        List<PduDataElectricEntity> electricList = pduDAO.getElectricListByDeviceId(sn);
        if (CollectionUtils.isEmpty(electricList)) {
            return map;
        }
        for (PduDataElectricEntity e : electricList) {
            DecimalFormat df = new DecimalFormat("0.0");
            StringBuffer param = new StringBuffer();
            param.append(electric).append(e.getBranch_number());
            map.put(param.toString(), String.valueOf(df.format((float) e.getBranch_electric() / 10)));
        }
        map.put("total_power", String.valueOf(totalPower));
        map.put("power", String.valueOf(totalPower));
        //基本信息
        Map<String, String> pdu = pduDAO.getPduByDeviceId(sn);
        if (null == pdu) {
            return map;
        }
        if (pdu.containsKey("frequency") && !StringUtil.isEmpty(pdu.get("frequency"))) {
            map.put("frequency", pdu.get("frequency"));
        }
        if (pdu.containsKey("electric_current") && !StringUtil.isEmpty(pdu.get("electric_current"))) {
            map.put("electric_current", pdu.get("electric_current"));
        }
        if (pdu.containsKey("voltage") && !StringUtil.isEmpty(pdu.get("voltage"))) {
            map.put("voltage", pdu.get("voltage"));
        }
        if (pdu.containsKey("active_power") && !StringUtil.isEmpty(pdu.get("active_power"))) {
            map.put("active_power", pdu.get("active_power"));
        }
        if (pdu.containsKey("no_work_power") && !StringUtil.isEmpty(pdu.get("no_work_power"))) {
            map.put("no_work_power", pdu.get("no_work_power"));
        }
        if (pdu.containsKey("inspecting_power") && !StringUtil.isEmpty(pdu.get("inspecting_power"))) {
            map.put("inspecting_power", pdu.get("inspecting_power"));
        }
        if (pdu.containsKey("power_factor") && !StringUtil.isEmpty(pdu.get("power_factor"))) {
            DecimalFormat df = new DecimalFormat("0.00");
            map.put("power_factor", df.format((double) Double.parseDouble(pdu.get("power_factor")) / 100));
        }
        if (pdu.containsKey("active_energy") && !StringUtil.isEmpty(pdu.get("active_energy"))) {
            map.put("active_energy", pdu.get("active_energy"));
        }
        if (pdu.containsKey("no_work_energy") && !StringUtil.isEmpty(pdu.get("no_work_energy"))) {
            map.put("no_work_energy", pdu.get("no_work_energy"));
        }
        return map;
    }

    public Map<String, String> getPduPowerInfo(String sn) {
        Map<String, String> map = new HashMap<>();
        Map<String, Map<String, String>> resultMap = getDyn();
        PDU.Builder pBuilder = PDU.newBuilder();
        if (resultMap != null && !"".equals(resultMap) && resultMap.size() != 0) {
            if ("JXCC001".equals(sn)) {
                Map<String, String> jxcc001Map = resultMap.get("6F9619FF-8B86-D011-B42D-00C04FC91211");
                pBuilder.setPower(stringBy10(jxcc001Map.get("1110"))).setBranchpower1(stringBy10(jxcc001Map.get("1025"))).setBranchpower2(stringBy10(jxcc001Map.get("1026"))).setBranchpower3(stringBy10(jxcc001Map.get("1027")))
                    .setBranchpower4(stringBy10(jxcc001Map.get("1028"))).setBranchpower5(stringBy10(jxcc001Map.get("1029"))).setBranchpower6(stringBy10(jxcc001Map.get("1030"))).setBranchpower7(stringBy10(jxcc001Map.get("1031")))
                    .setBranchpower8(stringBy10(jxcc001Map.get("1032"))).setBranchpower9(stringBy10(jxcc001Map.get("1033"))).setBranchpower10(stringBy10(jxcc001Map.get("1034"))).setBranchpower11(stringBy10(jxcc001Map.get("1035")))
                    .setBranchpower12(stringBy10(jxcc001Map.get("1036"))).setBranchpower13(stringBy10(jxcc001Map.get("1037"))).setBranchpower14(stringBy10(jxcc001Map.get("1038"))).setBranchpower15(stringBy10(jxcc001Map.get("1039")))
                    .setBranchpower16(stringBy10(jxcc001Map.get("1040")));
                serverInfoDao.insertPduInfos(sn, pduCurrent(stringBy10(jxcc001Map.get("1025"))), pduCurrent(stringBy10(jxcc001Map.get("1026"))), pduCurrent(stringBy10(jxcc001Map.get("1027"))), pduCurrent(stringBy10(jxcc001Map.get("1028"))),
                    pduCurrent(stringBy10(jxcc001Map.get("1029"))), pduCurrent(stringBy10(jxcc001Map.get("1030"))), pduCurrent(stringBy10(jxcc001Map.get("1031"))), pduCurrent(stringBy10(jxcc001Map.get("1032"))), pduCurrent(stringBy10(jxcc001Map.get("1033")))
                    , pduCurrent(stringBy10(jxcc001Map.get("1034"))), pduCurrent(stringBy10(jxcc001Map.get("1035"))), pduCurrent(stringBy10(jxcc001Map.get("1036"))), pduCurrent(stringBy10(jxcc001Map.get("1037"))), pduCurrent(stringBy10(jxcc001Map.get("1038")))
                    , pduCurrent(stringBy10(jxcc001Map.get("1039"))), pduCurrent(stringBy10(jxcc001Map.get("1040"))));
            }

            if ("JXCC002".equals(sn)) {
                Map<String, String> jxcc002Map = resultMap.get("6F9619FF-8B86-D011-B42D-00C04FC91212");
                pBuilder.setPower(stringBy10(jxcc002Map.get("1114"))).setBranchpower1(stringBy10(jxcc002Map.get("1042"))).setBranchpower2(stringBy10(jxcc002Map.get("1041"))).setBranchpower3(stringBy10(jxcc002Map.get("1040")))
                    .setBranchpower4(stringBy10(jxcc002Map.get("1039"))).setBranchpower5(stringBy10(jxcc002Map.get("1038"))).setBranchpower6(stringBy10(jxcc002Map.get("1037"))).setBranchpower7(stringBy10(jxcc002Map.get("1036")))
                    .setBranchpower8(stringBy10(jxcc002Map.get("1035"))).setBranchpower9(stringBy10(jxcc002Map.get("1034"))).setBranchpower10(stringBy10(jxcc002Map.get("1033"))).setBranchpower11(stringBy10(jxcc002Map.get("1032")))
                    .setBranchpower12(stringBy10(jxcc002Map.get("1031"))).setBranchpower13(stringBy10(jxcc002Map.get("1030"))).setBranchpower14(stringBy10(jxcc002Map.get("1029"))).setBranchpower15(stringBy10(jxcc002Map.get("1028")))
                    .setBranchpower16(stringBy10(jxcc002Map.get("1027")));
                serverInfoDao.insertPduInfos(sn, pduCurrent(stringBy10(jxcc002Map.get("1042"))), pduCurrent(stringBy10(jxcc002Map.get("1041"))), pduCurrent(stringBy10(jxcc002Map.get("1040"))), pduCurrent(stringBy10(jxcc002Map.get("1039"))),
                    pduCurrent(stringBy10(jxcc002Map.get("1038"))), pduCurrent(stringBy10(jxcc002Map.get("1037"))), pduCurrent(stringBy10(jxcc002Map.get("1036"))), pduCurrent(stringBy10(jxcc002Map.get("1035"))), pduCurrent(stringBy10(jxcc002Map.get("1034")))
                    , pduCurrent(stringBy10(jxcc002Map.get("1033"))), pduCurrent(stringBy10(jxcc002Map.get("1032"))), pduCurrent(stringBy10(jxcc002Map.get("1031"))), pduCurrent(stringBy10(jxcc002Map.get("1030"))), pduCurrent(stringBy10(jxcc002Map.get("1029")))
                    , pduCurrent(stringBy10(jxcc002Map.get("1028"))), pduCurrent(stringBy10(jxcc002Map.get("1027"))));
            }
        }
        map = pduBuilderToMap(pBuilder);
        if (map != null && !map.isEmpty()) {
            map.put("server_sn", sn);
        }
        return map;
    }

    /**
     * 获取动环数据
     *
     * @return
     */
    private Map<String, Map<String, String>> getDyn() {
        Map<String, Map<String, String>> resultMap = new HashMap<>();
        try {
            String loginResult = connectDyn();
            if (loginResult == null || "".equals(loginResult)) {
                logger.error("loginResult is null ");
                return resultMap;
            }
            String token = new JSONObject(loginResult).getJSONObject("data").get("token").toString();
            RequestData onlineData = new RequestData();
            onlineData.setVersion(PropertiesUtil.getValue("serverIp.properties", "version"));
            Map<String, String[]> map = new HashMap<>();
            String[] deviceGuids = PropertiesUtil.getArrayValue("serverIp.properties", "deviceGuids");
            map.put("space_guids", null);
            map.put("device_guids", deviceGuids);
            map.put("point_guids", null);
            onlineData.setData(map);
            String onlineJson = new JSONObject(onlineData).toString();
            String onlineResult = HttpUtil.postJson(PropertiesUtil.getValue("serverIp.properties", "urlOnlineDataUrl"), token, onlineJson);
            if (onlineResult == null || "".equals(onlineResult)) {
                logger.error("onlineResult is null ");
                return resultMap;
            }

            JSONArray devices = new JSONObject(onlineResult).getJSONObject("data").getJSONArray("devices");
            for (int i = 0; i < devices.length(); i++) {
                JSONObject jsonObject = devices.getJSONObject(i);
                JSONArray points = jsonObject.getJSONArray("points");
                Map<String, String> dataMap = new HashMap<String, String>();
                for (int j = 0; j < points.length(); j++) {
                    JSONObject point = points.getJSONObject(j);

                    dataMap.put(point.get("tag").toString(), point.get("value").toString());
                }
                resultMap.put(jsonObject.get("guid").toString(), dataMap);
            }
        } catch (Exception e) {
            logger.debug("post请求发送异常", e);
        }
        return resultMap;
    }

    private String connectDyn() {
        String loginResult = "";
        try {
            RequestData loginData = new RequestData();
            loginData.setVersion(PropertiesUtil.getValue("serverIp.properties", "version"));
            Map<String, Object> data = new HashMap<>();
            data.put("ip", PropertiesUtil.getValue("serverIp.properties", "userIp"));
            data.put("username", PropertiesUtil.getValue("serverIp.properties", "userUsername"));
            data.put("password", PropertiesUtil.getValue("serverIp.properties", "userPassword"));
            data.put("login_time", System.currentTimeMillis() / 1000);
            loginData.setData(data);
            String loginRequest = new JSONObject(loginData).toString();
            loginResult = HttpUtil.postJson(PropertiesUtil.getValue("serverIp.properties", "loginUrl"), null, loginRequest);
        } catch (Exception e) {
            logger.debug("post请求发送异常", e);
        }

        return loginResult;
    }


    private String stringBy10(String str) {
        if (Double.valueOf(str) == 0) {
            return str;
        }
        str = String.valueOf(Double.valueOf(str) * 1000);
        return str;
    }

    private int pduCurrent(String str) {
        if (Double.valueOf(str) == 0 || StringUtil.isEmpty(str)) {
            return 0;
        }
        BigDecimal bigDecimal = new BigDecimal(str);
        BigDecimal num = new BigDecimal(0.22);
        int result = bigDecimal.divide(num, BigDecimal.ROUND_HALF_UP).intValue();
        return result;
    }

    private Map<String, String> airBuilderToMap(AirConditioner.Builder builder) {
        /**获取空调动态数据*/


        HashMap<String, String> map = new HashMap<>();
        map.put("room_temperature", builder.getRoomTemperature());
        map.put("outdoor_temperature", builder.getOutdoorTemperature());
        map.put("delivery_temperature", builder.getDeliveryAirTemperature());
        map.put("chilled_water_temperature", builder.getChilledWaterTemperature());
        map.put("hot_water_temperature", builder.getHotWaterTemperature());
        map.put("relative_humidity", builder.getRoomRelativeHumidity());
        map.put("outlet_chilled_water_temperature", builder.getOutletChilledWaterTemperature());
        map.put("circuit1_evaporating_pressure", builder.getCircuit1EvaporatingPressure());
        map.put("circuit2_evaporating_pressure", builder.getCircuit2EvaporatingPressure());
        map.put("circuit1_ absorption_temperature", builder.getCircuit1SuctionTemperature());
        map.put("circuit2_ absorption_temperature", builder.getCircuit2SuctionTemperature());
        map.put("circuit1_overheating_temperature", builder.getCircuit1Superheat());
        map.put("circuit2_overheating_temperature", builder.getCircuit2Superheat());
        map.put("cooling_water_valve_ramp", builder.getColdWaterValveRamp());
        map.put("heating_water_valve_ramp", builder.getHotWaterValveRamp());
        map.put("evaporating_fan_rpm", builder.getEvaporatingFanSpeed());
        map.put("refrigerating_setpoint", builder.getCoolingSetpoint());
        map.put("refrigerating_sensitivity", builder.getCoolingSensitivity());
        map.put("secondary_refrigerating_setpoint", builder.getSecondCoolingSetpoint());
        map.put("secondary_refrigerating_sensitivity", builder.getCoolingSensitivity());
        map.put("secondary_heating_setpoint", builder.getSecondHeatingSetpoint());
        map.put("secondary_heating_sensitivity", builder.getHeatingSensitivity());
        map.put("high_temperature_alarm_threshold", builder.getHighRoomTemperatureAlarmThreshold());
        map.put("low_temperature_alarm_threshold", builder.getLowRoomTemperatureAlarmThreshold());
        map.put("setback_mode_refrigerating_setpoint", builder.getSetbackModeCoolingSetpoint());
        map.put("setback_mode_heatting_setpoint", builder.getSetbackModeHeatingSetpoint());
        map.put("cw_dehumidification_threshold", builder.getCwSetpointToStartDehumidification());
        map.put("cw_high_temperature_alarm_threshold", builder.getCwHighTemperatureAlarmThreshold());
        map.put("cw_start_setpoint", builder.getCwSetpointToStartCwOperatingMode());
        map.put("rad_setpoint_energy_saving_mode", builder.getRadcoolerSetpointInEnergySavingMode());
        map.put("rad_setpoint_dx_mode", builder.getRadcoolerSetpointInDxMode());
        map.put("minimum_temperature_for_airflow_delivery", builder.getDeliveryTemperatureLowLimitSetpoint());
        map.put("delta_temperature_for_inner_heat_exchanger", builder.getDeltaTemperatureForAutomaticLocalChangeover());
        map.put("serial_transmission_offset", builder.getSerialTransmissionOffset());
        map.put("power", String.valueOf(builder.getPower()));
        return map;

    }

    private Map<String, String> pduBuilderToMap(PDU.Builder builder) {
        HashMap<String, String> map = new HashMap<>();
        map.put("branch_power1", builder.getBranchpower1());
        map.put("branch_power2", builder.getBranchpower2());
        map.put("branch_power3", builder.getBranchpower3());
        map.put("branch_power4", builder.getBranchpower4());
        map.put("branch_power5", builder.getBranchpower5());
        map.put("branch_power6", builder.getBranchpower6());
        map.put("branch_power7", builder.getBranchpower7());
        map.put("branch_power8", builder.getBranchpower8());
        map.put("branch_power9", builder.getBranchpower9());
        map.put("branch_power10", builder.getBranchpower10());
        map.put("branch_power11", builder.getBranchpower11());
        map.put("branch_power12", builder.getBranchpower12());
        map.put("branch_power13", builder.getBranchpower13());
        map.put("branch_power14", builder.getBranchpower14());
        map.put("branch_power15", builder.getBranchpower15());
        map.put("branch_power16", builder.getBranchpower16());
        map.put("branch_power17", builder.getBranchpower17());
        map.put("branch_power18", builder.getBranchpower18());
        map.put("branch_power19", builder.getBranchpower19());
        map.put("branch_power20", builder.getBranchpower20());
        map.put("branch_power21", builder.getBranchpower21());
        map.put("branch_power22", builder.getBranchpower22());
        map.put("branch_power23", builder.getBranchpower23());
        map.put("branch_power24", builder.getBranchpower24());
        map.put("total_power", builder.getPower());
        map.put("power", builder.getPower());
        return map;
    }
}
